package session1.practises;

import java.util.Arrays;
import java.util.Scanner;

class ConcurrentSortProgram {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入数组长度：");
        int length = scanner.nextInt();
        int[] array = new int[length];
        System.out.println("请输入数组元素：");
        for (int i = 0; i < length; i++) {
            array[i] = scanner.nextInt();
        }
        System.out.print("请输入拆分部分的数量：");
        int numParts = scanner.nextInt();
        ConcurrentSorter sorter = new ConcurrentSorter(array, numParts);
        sorter.sort();
        int[] sortedArray = sorter.getSortedArray();
        System.out.println("排序结果：" + Arrays.toString(sortedArray));
    }
}
class ConcurrentSorter {
    private int[] array;
    private int numParts;
    private int[] sortedArray;

    public ConcurrentSorter(int[] array, int numParts) {
        this.array = array;
        this.numParts = numParts;
        this.sortedArray = new int[array.length];
    }

    public void sort() {
        Thread[] threads = new Thread[numParts];
        int partSize = array.length / numParts;
        int remainingElements = array.length % numParts;
        int startIndex = 0;
        for (int i = 0; i < numParts; i++) {
            int endIndex = startIndex + partSize;
            if (i < remainingElements) {
                endIndex++;
            }
            int[] subArray = Arrays.copyOfRange(array, startIndex, endIndex);
            threads[i] = new Thread(() -> {
                Arrays.sort(subArray);
            });
            threads[i].start();
            startIndex = endIndex;
        }
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        mergeArrays();
    }
    private void mergeArrays() {
        int partSize = array.length / numParts;
        int remainingElements = array.length % numParts;
        int startIndex = 0;
        for (int i = 0; i < numParts; i++) {
            int endIndex = startIndex + partSize;
            if (i < remainingElements) {
                endIndex++;
            }
            int[] subArray = Arrays.copyOfRange(array, startIndex, endIndex);
            System.arraycopy(subArray, 0, sortedArray, startIndex, subArray.length);
            startIndex = endIndex;
        }
        Arrays.sort(sortedArray);
    }
    public int[] getSortedArray() {
        return sortedArray;
    }
}